// DsmTimeServer.cc
// author: CASO-04

#include "TcpListener.h"
#include "Dsm.h"

#define BUFFER_SIZE 1024

extern "C"
{
	#include <sys/time.h>
}

void usage()
{
	cout << "Usage: DsmTimeServer <dsm-server-port> <servername>" << endl;
	exit(1);
}


int main(int argc, char** argv)
{

	if (argc != 3)
	{
		usage();
	}

	// Hacer lookup dsm.deusto.es 
	PracticaCaso::DsmDriver * driver = new PracticaCaso::DsmDriver("127.0.0.1", atoi(argv[1]), argv[2]);
	PracticaCaso::DsmData data;
	
	// Reservar memoria
	
	// Sytem time
	struct timeval t;
	struct timezone tzp;
	
	char time[100];
	struct timeval tv;
	time_t curtime;
		
	// Bucle infinito

	try
	{
		driver->dsm_malloc("GLOBAL_TIMESTAMP", sizeof(time));
		while (true)
		{
			// Get sytem time
			gettimeofday (&tv, &tzp);
			curtime=tv.tv_sec;
			strftime(time,100,"%d-%m-%Y, %H:%M:%S",localtime(&curtime));
			cout << "new system time set " << time << endl;

			try
			{
				driver->dsm_put("GLOBAL_TIMESTAMP", (void *)time, sizeof(time)); 
			}
			catch (DsmException dsme)
			{
				cerr << "ERROR: dsm_put(\"GLOBAL_TIMESTAMP\", time, " << sizeof(time) << ")): " << dsme << endl;
				driver->dsm_free("GLOBAL_TIMESTAMP");
				exit(1);
			}
			sleep(1);
		}
	}
	catch (DsmException dsme)
	{
		// There may be several processes doing a dsm_malloc, only the first one will succeed 
		cerr << "ERROR in dsm_malloc(\"GLOBAL_TIMESTAMP\", sizeof(" << sizeof(time) << ")): " << dsme << endl;
		exit(1);
	}
	
	driver->dsm_free("SumOddNums");
	cout << "Sleeping for a second before finishing ..." << endl;
	sleep(1);
	delete driver;
}

